package main.java.br.com.projeto.domain.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.PersistenceException;

import main.java.br.com.projeto.domain.entity.Venda;

public class DaoVenda extends Dao<Venda>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6111885302324856223L;

	public DaoVenda() {
		super(Venda.class);
	}
	
	public Venda findByPK(Long numeroNota, String numeroSerie) {
		String hql = "select Venda from Venda venda "
				+ "where venda.numeroNota = :numeroNota " 
				+ "and venda.numeroSerie = :numeroSerie ";

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("numeroNota", numeroNota);
		parameters.put("numeroSerie", numeroSerie);

		return this.findOneResult(hql, parameters).get(0);
	}
	
	public Venda insert(Venda entity) {
		try {
			this.beginTransaction();		
			getManager().persist(entity);
			this.commit();
			this.closeTransaction();
			return entity;
		} catch (PersistenceException e) {
			return this.update(entity);
		} catch (Exception e2) {
			this.rollback();
			e2.printStackTrace();
			return null;
		}
	}
	
	public List<Venda> listByFilter(Long numeroNota, Long numeroSerie, String cliente, Date dataEmissao) {
		String hql = "select venda from Venda venda "
				+ "where (venda.numeroNota = :numeroNota or :numeroNota = 0) "
				+ "and (venda.numeroSerie = :numeroSerie or :numeroSerie = 0) "
				+ "and (lower(venda.cliente.nome) like '%' || lower(cast(:cliente  as string)) || '%' or :cliente = null) "
				+ "and (venda.emissao = :dataEmissao or cast(:dataEmissao as date) = null)";

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("numeroNota", numeroNota);
		parameters.put("numeroSerie", numeroSerie);
		parameters.put("cliente", cliente);
		parameters.put("dataEmissao", dataEmissao);

		return this.findOneResult(hql, parameters);
	}
}
